package com.example.common.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;

import com.coszero.utilslibrary.app.AppManager;
import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.StringUtils;
import com.example.common.config.AppControl;
import com.example.common.utils.eventbus.EventUtils;
import com.example.common.widget.MyToolBar;
import com.example.commonlib.R;

import butterknife.ButterKnife;

/**
 * Desc： 父类
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/8/12 0012 14:41
 */
public abstract class BaseActivity extends AppCompatActivity {
    public static Class<?> currentActivity;
    private String TAG = this.getClass().getSimpleName();
    protected Context mContext;
    protected Activity mActivity;
    private MyToolBar myToolBar;
    private EventUtils eventUtils;
    /**
     * 是否显示返回键
     */
    private boolean showBack = true;
    /**
     * 标题
     */
    private String mainTitle;

    static {
        //开启矢量图支持
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    // <editor-fold desc="生命周期" defaultstate="collapsed">
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        mContext = this;
        mActivity = this;
        setContentView(getLayoutResource());
        ButterKnife.bind(this);
        initEventBus();
        myToolBar = findViewById(R.id.my_toolbar);
        try {
            initTitle();
            initView();
            initPresenter();
            initData();
        } catch (Exception e) {
            e.printStackTrace();
            LogX.e("### BaseActivity：", e.getMessage());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        currentActivity = getClass();
    }

    @Override
    public void onDestroy() {
        AppManager.getAppManager().removeActivity(this);
        if (AppControl.USE_EVENTBUS) {
            eventUtils.unregisterEventBus(this);
        }
        super.onDestroy();
    }

    //</editor-fold>

    private void initEventBus() {
        if (AppControl.USE_EVENTBUS) {
            if (eventUtils == null) {
                eventUtils = new EventUtils();
            }
            eventUtils.registerEventBus(this);
        }
    }

    /**
     * 用来初始化mvp模式的
     */
    protected void initPresenter() {
    }


    /**
     * 退出app
     */
    public void exitApp() {
        AppManager.getAppManager().exitApp(getApplicationContext(), 0);
        System.out.println("#exit app");
    }


    // <editor-fold desc="标题设置" defaultstate="collapsed">

    /**
     * 需要重写OnCreate()
     *
     * @param showBack 是否显示返回键
     */
    public void setShowBack(boolean showBack) {
        this.showBack = showBack;
    }

    protected void initTitle() {
        if (myToolBar != null) {
            /*if (showBack) {
                myToolBar.setLeftIconDrawable(R.drawable.ic_sl_shop_black_title_back);
            }*/
            if (!StringUtils.isEmpty(mainTitle)) {
                setTitle(mainTitle);
            }
            setSupportActionBar(myToolBar);
            myToolBar.setLeftTitleClickListener(v -> finish());
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        LogX.d("###", "设置标题" + title);
        //重新actionbar的方法
        if (myToolBar != null) {
            myToolBar.setMainTitle(title.toString());
        } else {
            this.mainTitle = title.toString();
        }
    }

    @Override
    public void setTitleColor(int textColor) {
        getMyToolBar().setMainTitleColor(textColor);
    }

    @Override
    public void setTitle(int titleId) {
        //重写方法
        setTitle(getResources().getString(titleId));
    }

    public void setTitleDrawable(Drawable drawable) {
        myToolBar.setMainTitleDrawable(drawable);
    }

    public void setRightText(int textId, View.OnClickListener listener) {
        if (myToolBar != null) {
            myToolBar.setRightTitleText(getString(textId));
            myToolBar.setRightTitleClickListener(listener);
        }
    }

    public void setRightText(String title, View.OnClickListener listener) {
        if (myToolBar != null) {
            myToolBar.setRightTitleText(title);
            myToolBar.setRightTitleClickListener(listener);
        }
    }

    public void setRightText(int textId, int colorId, View.OnClickListener listener) {
        if (myToolBar != null) {
            myToolBar.setRightTitleText(getString(textId));
            myToolBar.setRightTitleClickListener(listener);
            myToolBar.setRightTitleColor(colorId);
        }
    }

    public void setRightImage(int resourceId, View.OnClickListener listener) {
        if (myToolBar != null) {
            myToolBar.setRightIconDrawable(resourceId);
            myToolBar.setRightTitleClickListener(listener);
        }
    }

    public void setLeftImage(int resourceId) {
        setLeftImage(resourceId, v -> finish());
    }

    public void setLeftImage(int resourceId, View.OnClickListener listener) {
        if (myToolBar != null) {
            myToolBar.setLeftIconDrawable(resourceId);
            myToolBar.setLeftTitleClickListener(listener);
        }
    }

    public MyToolBar getMyToolBar() {
        if (null != myToolBar) {
            return myToolBar;
        }
        return null;
    }
//</editor-fold>

    /**
     * 设置透明状态栏（API21，5.0之后才能用）
     *
     * @param color 通知栏颜色，完全透明填 Color.TRANSPARENT 即可
     * @param isLightMode 是否为亮色模式（黑色字体，需要6.0 以后支持，否则显示无效）
     */
    protected void requestTranslucentStatusBar(int color, boolean isLightMode) {
        //大于5.0才设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //大于6.0 并且是亮色模式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isLightMode) {
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            } else {
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
            //因为5.0不支持黑色字体模式，如果设置成透明色则字体回看不到，设置成半透明黑色
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && color == Color.TRANSPARENT) {
                color = Color.parseColor("#44000000");
            }
            getWindow().setStatusBarColor(color);
        }
    }

    /**
     * 隐藏状态栏开关
     *
     * @param on
     */
    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 设置缺口屏的显示模式,最好在onCreate中使用
     * -默认不可使用刘海区域，非全面平可以使用：MODE_DEFAULT=0
     * -允许延伸到刘海区域SHORT_EDGES=1
     * -不允许使用刘海区域NEVER=2
     */
    protected void setDisplayCutouMode(int showMode) {
        if (Build.VERSION.SDK_INT >= 28) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            if (showMode != 0) {
                lp.layoutInDisplayCutoutMode = showMode;
            } else {
                lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            }
            getWindow().setAttributes(lp);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
    }

    // <editor-fold desc="抽象方法" defaultstate="collapsed">
    protected abstract int getLayoutResource();

    public abstract void initView();

    protected abstract void initData();
//</editor-fold>
}
